import React, { useState, useRef, useEffect } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Row, Image, Button, Modal, Divider, message, Radio, Pagination, List, Card, Typography } from 'antd';
import styles from './style.less';
import { useRequest,Link,request } from 'umi';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { queryDrawing, updateDrawing, addDrawing, batchUpdateDrawing } from '@/services/drawing';
import { queryDictByType } from '@/services/dict';
const { confirm } = Modal;
const { Meta } = Card;
import { QueryFilter, ProFormText, ProFormSelect } from '@ant-design/pro-form';
import filelogo from '/public/file.jpg';

import FileViewer from 'react-file-viewer';

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addDrawing(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 批量更新
 * @param fields
 */
const batchUpdate = async (fields: any, resetForm: any) => {
  const hide = message.loading('正在添加');
  try {
    await batchUpdateDrawing(fields);
    resetForm();
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};




/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateDrawing(fields);
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};


//删除单个
const remove = async (id: number) => {
  console.log(id)
  const hide = message.loading('正在删除');
  try {
    await updateDrawing({ drawingId: id, deleteFlag: 1 });
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};


export default () => {

  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const [typeEnumValues, setTypeEnumValues] = useState({});
  const [typeSelectValues, setTypeSelectValues] = useState([]);
  const [typeValues, setTypeValues] = useState<API.DictItem[]>([]);
  const [drawingData, setDrawingData] = useState<Array<API.DrawingItem>>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [model, setModel] = useState<string>('2')
  const [total, setTotal] = useState<number>(0);
  const [dateSourse, setDateSourse] = useState<API.DrawingItem>();
  const [searchDate, setSearchDate] = useState();
  const [pageSize, setPageSize] = useState<number>(20);
  const [current, setCurrent] = useState<number>(1);

  const optionsSel = [
    { label: '表格模式', value: '2' },
    { label: '陈列模式', value: '1' },
  ];


  function onChangeSel(e) {
    setModel(e.target.value);
  }

// 下载按钮点击事件
const exportExcel = async (item:API.DrawingItem) => {
    let  url=`/drawing/download/${item.drawingId}`;
      fetch(`/drawing/${item.drawingId}`, {  method: 'GET'
                }).then((res) => {
          if(res.status==200){
            // const url = window.URL.createObjectURL(new Blob([res]));
            console.log(url)
            const link = document.createElement('a'); //创建a标签
            link.style.display = 'none';
            link.href = url; // 设置a标签路径
            link.download = `${item.drawingName}`; //设置文件名， 也可以这种写法 （link.setAttribute('download', '名单列表.xls');
            document.body.appendChild(link);
            link.click();
            URL.revokeObjectURL(link.href); // 释放 URL对象
            document.body.removeChild(link);

          }else{
             alert('文件不存在');
          }
         }).catch((error) => {
            console.log(error)
            alert('文件下载失败');
          });
        
       
   
  };


  const getDrawing = function (record) {
    if (record.suffix == 'png' || record.suffix == 'jpg' || record.suffix == 'jpeg') {
      return (<Image style={{ width: 100, height: 60 }} src={record.path}></Image>);
    } else if(record.suffix == 'pdf') {
      // return (<Tooltip placement="topLeft" title="请下载文件到本地使用第三方工具预览"> <a target="_blank" href={"http://localhost:8080/fsmsapi/drawing/download/" + record.drawingId}>{record.title}</a></Tooltip>);
       return ( <a  target = "_blank"  href={record.path} ><Image style={{ width: 100, height: 60 }} src={filelogo} preview={false}></Image></a>);
    }else{
       <Image style={{ width: 100, height: 60 }} src={filelogo} preview={false}></Image>
    }
  }

  const columns: ProColumns<API.DrawingItem>[] = [
    {
      title: '图纸分类',
      dataIndex: 'typeId',
      valueType: 'select',
      valueEnum: typeEnumValues
    },
    {
      title: '图纸名称',
      dataIndex: 'drawingName',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: rowIndex > 2 ? [{ required: true, message: '此项为必填项' }] : [],
        };
      }
    },
    {
      title: '图纸',
      search: false,
      dataIndex: 'attachCode',
      render: (text, record, _, action) => [
        getDrawing(record)
      ]
    }, {
      title: '文件类型',
      dataIndex: 'suffix',
      search: false,
    },
    {
      title: '图纸大小(MB)',
      dataIndex: 'size',
      search: false,
      render: (text, record, _, action) => {
        return (record.size / 1024/1024).toFixed(1)
      }
    },
    {
      title: '上传人',
      search: false,
      dataIndex: 'realName',

    },
    {
      title: '上传日期',
      search: false,
      dataIndex: 'uploadTime',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => (
        <>
          <a
            // href={"http://localhost:8080/drawing/download/" + record.drawingId}
            onClick={()=>exportExcel(record)}
          >
            {record.relativePath == null ? "" : " 下载 "}
          </a>
          <Divider type="vertical" />
          <a
            onClick={async () => {
              handleUpdateModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a onClick={async () => {
            confirm({
              title: '确定要删除吗?',
              icon: <ExclamationCircleOutlined />,
              async onOk() {
                await remove(record.drawingId);
                getTableDate({});
              },
              onCancel() {
                console.log('Cancel');
              },
            });
          }}> 删除 </a>

        </>
      )
    },
  ];

  const setSelectData = async () => {
    const dtype = await queryDictByType({ "type": "3" });
    let pdata = [];
    let edata = {};
    if (dtype && dtype.length > 0) {
      dtype.forEach(item => {
        edata[item.dictCode] = { text: item.dictValue };
        pdata.push({ label: item.dictValue, value: item.dictCode })
      });
    }
    setTypeSelectValues(pdata)
    setTypeEnumValues(edata);
    setTypeValues(dtype);
  };

  useEffect(() => {
    setSelectData();
  }, []);

  async function onChange(c, ps) {
    if (!loading) {
      setCurrent(c);
      setPageSize(ps);
    }
  }

  const { run } = useRequest(() => getTableDate({}), { manual: true });
  useEffect(() => {
    run();
  }, [pageSize, current, searchDate]);


  async function getTableDate(params) {
    setLoading(true);
    let tabledate = await queryDrawing(
      {
        current: current,
        pageSize: pageSize,
        ...searchDate,
        ...params

      });

    console.log(tabledate)
    setDateSourse(tabledate.data);
    setTotal(tabledate.total);
    setLoading(false);
  }


  const list = dateSourse || [];
  const cardList = list && (
    <List<API.DrawingItem>
      rowKey="drawingId"
      loading={loading}
      grid={{
        gutter: 16,
        xs: 1,
        sm: 2,
        md: 5,
        lg: 6,
        xl: 6,
        xxl: 6,
      }}
      dataSource={dateSourse}

      renderItem={(item) => (
        item.suffix != 'jpeg' ?
          <List.Item key={item.drawingId}>
            <Card style={{ width: '100%' }} hoverable={true} cover={<Image preview={false} placeholder={true} height={240} src={filelogo} />}   >
              <Meta title={
              <div style={{display: 'flex',justifyContent: 'space-between'}}><div className={styles.overhidden}>{item.drawingName} </div>
              { item.suffix=="pdf"?
                // <Link target = "_blank" to={"/preview/"+ item.drawingId}>预览</Link>
                <a  target = "_blank"  href={item.path} >预览</a> :  
                <a  
                 onClick={()=>exportExcel(item)}
                   //href={"http://localhost:8080/drawing/download/" + item.drawingId}
                 >
                    {item.relativePath == null ? "" : " 下载 "}
                </a>}
              </div>} />
            </Card>
          </List.Item> : <List.Item>
       

          {/* <object width="250" height="250" data={item.filePath} ></object> */}
            <Card style={{ width: '100%' }} hoverable={true} cover={<Image height={240} src={item.path} />}>
              <Meta
                title={item.drawingName}
              />
            </Card>
          </List.Item>
      )}
    />
  );


  return (
    <div className={styles.main}>

      <Row style={{ display: 'flex', flexDirection: 'row', justifyContent: 'flex-end', marginTop: '10px' }}>
        <Radio.Group
          options={optionsSel}
          onChange={onChangeSel}
          value={model}
          optionType="button"
          buttonStyle="solid"
        />
      </Row>
      <div style={{ padding: '16px 0' }}>
        <QueryFilter defaultCollapsed labelWidth={'auto'} onFinish={async (values: any) => {
          console.log(values)
          setSearchDate(values);
        }}>
          <ProFormSelect name="typeId" label="图纸分类" options={typeSelectValues} />
          <ProFormText name="drawingName" label="图纸名称" />
        </QueryFilter>
        <div className={styles.flexend}>
          <Button icon={<PlusOutlined />} type="primary" onClick={() => handleModalVisible(true)}>
            上传图纸
          </Button>
        </div>
      </div>

      {model == '1' ?
        cardList :
        <ProTable
          rowKey="drawingId"
          actionRef={actionRef}
          search={false}
          toolBarRender={false}
          dataSource={dateSourse}
          columns={columns}
          pagination={false}
        />
      }
      <Row style={{ display: 'flex', flexDirection: 'row', justifyContent: 'flex-end', marginRight: '20px' }} >
        <Pagination
          size="small"
          total={total}
          defaultPageSize={pageSize}
          onChange={onChange}
          current={current}
          showSizeChanger
        />
      </Row>

      <CreateForm
        onSubmit={async (value, resetForm) => {
          const success = await batchUpdate(value, resetForm);
          if (success) {
            handleModalVisible(false);
            getTableDate({});
          }
        }}
        onCancel={() => handleModalVisible(false)}
        removeImage={remove}
        typeValues={typeValues}
        modalVisible={createModalVisible}
        reloadType={setSelectData}

      />

      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setFormValues({});
              getTableDate({});
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
          typeValues={typeValues}
        />
      ) : null}


    </div>
  );
};